package com.sk.weichat.ui.account;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.sk.weichat.R;
import com.sk.weichat.bean.Prefix;
import com.sk.weichat.db.InternationalizationHelper;
import com.sk.weichat.sortlist.SideBar;
import com.sk.weichat.sortlist.SortHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.util.Constants;
import com.sk.weichat.view.ClearEditText;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;


/**
 * Created by Administrator on 2017/4/21 0021.
 * 选择国家区号
 */
public class SelectPrefixActivity extends BaseActivity implements AdapterView.OnItemClickListener {

    public static final int RESULT_MOBILE_PREFIX_SUCCESS = 110;
    public static final int REQUEST_MOBILE_PREFIX_LOGIN = 11123;
    private List<Prefix> prefixList;// 所有的国家
    private List<Prefix> searchResult;// 搜索的结果集合
    private int lvScrollPosition;

    private ClearEditText searchEdt;
    private ListView mLv;
    private PrefixAdapter prefixAdapter;
    private SideBar mSideBar;
    private TextView mTextDialog, tvSearchTitle, tvHotSide, tvSearchNone;
    private LinearLayout linearRight;

    public SelectPrefixActivity() {
        noLoginRequired();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.a_act_selectaddr);
        initView();
    }

    private void initView() {
        getSupportActionBar().hide();
        findViewById(R.id.tv_cancel_search).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        searchEdt = findViewById(R.id.search_edit);
        searchEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                search();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        mLv = findViewById(R.id.lv_addr);
        prefixList = InternationalizationHelper.getPrefixList();
        prefixAdapter = new PrefixAdapter(prefixList);
        mLv.setAdapter(prefixAdapter);

        mLv.setOnItemClickListener(this);
        mSideBar = findViewById(R.id.sidebar_phone);
        mTextDialog = findViewById(R.id.text_dialog_phone);
        mSideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = prefixAdapter.getFirstPosition(s.charAt(0));
                if (position != -1) {
                    mLv.setSelection(position);
                    tvHotSide.setBackgroundResource(0);
                    tvHotSide.setTextColor(SelectPrefixActivity.this.getResources().getColor(R.color.my_black));
                    showTextDialog(s);
                }
            }
        });
        linearRight = findViewById(R.id.linear_act_right);
        tvSearchTitle = findViewById(R.id.tv_search_title);
        tvSearchNone = findViewById(R.id.tv_search_none);
        tvHotSide = findViewById(R.id.tv_hot_side);
        findViewById(R.id.ll_hot_zone).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLv.setSelection(0);
                tvHotSide.setTextColor(SelectPrefixActivity.this.getResources().getColor(R.color.white));
                tvHotSide.setBackgroundResource(R.drawable.bg_circle_purple);
            }
        });
        search();
        mLv.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (firstVisibleItem + visibleItemCount != totalItemCount) {
                    String firstStr = prefixAdapter.getFirstStr(firstVisibleItem);
                    if (!TextUtils.isEmpty(firstStr)){
                        if (!firstStr.equals("0")) {//不是热门地区
                            tvHotSide.setBackgroundResource(0);
                            tvHotSide.setTextColor(SelectPrefixActivity.this.getResources().getColor(R.color.my_black));
                            if (firstStr != null && !firstStr.equals("")) {
                                mSideBar.searchByFirstStr(firstStr);
                                if (firstVisibleItem != 0) {
                                    String strLast = prefixAdapter.getFirstStr(firstVisibleItem - 1);
                                    String strSec = prefixAdapter.getFirstStr(firstVisibleItem + 1);
                                    if (lvScrollPosition < firstVisibleItem) {
                                        if (!firstStr.equals(strLast)) {
                                            showTextDialog(firstStr);
                                        }
                                    } else if (lvScrollPosition > firstVisibleItem) {
                                        if (!firstStr.equals(strSec)) {
                                            showTextDialog(firstStr);
                                        }
                                    }
                                }
                            }
                        } else {
                            mSideBar.searchByFirstStr(firstStr);
                            tvHotSide.setTextColor(SelectPrefixActivity.this.getResources().getColor(R.color.white));
                            tvHotSide.setBackgroundResource(R.drawable.bg_circle_purple);
                        }
                    }
                }
                lvScrollPosition = firstVisibleItem;
            }
        });
    }

    private void showTextDialog(String s) {
        mTextDialog.setText(s);
        mTextDialog.setVisibility(View.VISIBLE);
        mHandler.removeMessages(0);
        mHandler.sendEmptyMessageDelayed(0, 100);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    AlphaAnimation aa = new AlphaAnimation(1.0f, 0.0f);//创建一个AlphaAnimation 对象，渐变从1->0
                    aa.setDuration(1000);//设置持续时间
                    aa.setFillAfter(true);
                    mTextDialog.startAnimation(aa);
                    mTextDialog.setVisibility(View.GONE);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Prefix prefixbean = (Prefix) prefixAdapter.getItem(i);
        int prefix = prefixbean.getPrefix();
        sendResult(prefix);
    }

    private void search() {
        String country = searchEdt.getText().toString().trim();
        Map<String, Integer> existMap = new HashMap<>();
        if (!TextUtils.isEmpty(country)) {
            // 变为搜索状态
            linearRight.setVisibility(View.GONE);
            searchResult = InternationalizationHelper.getSearchPrefix(country);
            prefixAdapter.setData(searchResult);
            SortHelper.toSortedModelList(searchResult, existMap, Prefix::getEnName);
            if (searchResult != null && searchResult.size() > 0) {
                tvSearchTitle.setVisibility(View.VISIBLE);
                tvSearchNone.setVisibility(View.GONE);
            } else {
                tvSearchTitle.setVisibility(View.GONE);
                tvSearchNone.setVisibility(View.VISIBLE);
                tvSearchNone.setText("找不到“" + country + "”相关国家/地区");
            }
        } else {
            linearRight.setVisibility(View.VISIBLE);
            tvSearchTitle.setVisibility(View.GONE);
            tvSearchNone.setVisibility(View.GONE);
            prefixList = InternationalizationHelper.getPrefixList();
            getHotArea();
            prefixAdapter.setData(prefixList);
            SortHelper.toSortedModelList(prefixList, existMap, Prefix::getEnName);
        }
        mSideBar.setExistMap(existMap);
    }

    //热门地区/国家
    private void getHotArea() {
        List<Prefix> hotList = new ArrayList<>();
        //根据下标顺序插入相应热门国家
        int[] indexArr = {71,65,201,10,171,102,189,97,114,85,206,38};
        for (int i = 0; i < indexArr.length; i++) {
            Prefix prefix = new Prefix();
            prefix.setCountry(prefixList.get(indexArr[i]).getCountry());
            prefix.setPrefix(prefixList.get(indexArr[i]).getPrefix());
            prefix.setEnName("0");//设置热门国家的字母为0
            hotList.add(prefix);
        }
        for (int i = 0; i < hotList.size(); i++) {
            prefixList.add(0, hotList.get(i));
        }
    }

    private void sendResult(int mobliePrefix) {
        Intent intent = new Intent();
        intent.putExtra(Constants.MOBILE_PREFIX, mobliePrefix);
        setResult(RESULT_MOBILE_PREFIX_SUCCESS, intent);
        finish();
    }

    private class PrefixAdapter extends BaseAdapter {
        private List<Prefix> data;

        public PrefixAdapter(List<Prefix> data) {
            this.data = data;
        }

        //根据首字母的获取该首字母item的第一条数据
        public int getFirstPosition(int section) {
            if (data != null && data.size() > 0) {
                for (int i = 0; i < data.size(); i++) {
                    String sortStr = data.get(i).getEnName();
                    char firstChar = sortStr.toUpperCase().charAt(0);
                    if (firstChar == section) {
                        return i;
                    }
                }
            }
            return -1;
        }

        public String getFirstStr(int position) {
            if (data != null && data.size() > 0 && position <= data.size()) {
                String sortStr = data.get(position).getEnName();
                if (!TextUtils.isEmpty(sortStr)) {
                    return sortStr.substring(0, 1);
                }
            }
            return null;
        }

        public void setData(List<Prefix> data) {
            this.data = data;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return data == null ? 0 : data.size();
        }

        @Override
        public Object getItem(int position) {
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(mContext, R.layout.a_item_resume_fnid, null);
                holder.tvCategoryTitle = convertView.findViewById(R.id.tv_category_title);
                holder.tvTitle = convertView.findViewById(R.id.tv_title_fnid_name);
                holder.tvNumber = convertView.findViewById(R.id.tv_area_code);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            if (Locale.getDefault().getLanguage().equals("en")) {
                holder.tvTitle.setText(data.get(position).getEnName());
            } else {
                if (!TextUtils.isEmpty(data.get(position).getEnName()) && getFirstStr(position).equals("0")) {
                    holder.tvTitle.setText(data.get(position).getCountry());
                } else if (!TextUtils.isEmpty(data.get(position).getEnName())) {
                    holder.tvTitle.setText(data.get(position).getCountry() + "(" + data.get(position).getEnName() + ")");
                } else {
                    holder.tvTitle.setText(data.get(position).getCountry());
                }
            }
            holder.tvNumber.setText("+" + data.get(position).getPrefix());
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) holder.tvNumber.getLayoutParams();
            if (!TextUtils.isEmpty(data.get(position).getEnName())) {//全部地区/国家
                lp.rightMargin = 58;
                holder.tvNumber.setLayoutParams(lp);
                if (position == 0 && getFirstStr(position).equals("0")) {
                    holder.tvCategoryTitle.setVisibility(View.VISIBLE);
                    holder.tvCategoryTitle.setText("热门");
                } else if (position > 0 && !getFirstStr(position).equals(getFirstStr(position - 1))) {
                    holder.tvCategoryTitle.setVisibility(View.VISIBLE);
                    holder.tvCategoryTitle.setText(getFirstStr(position));
                } else {
                    holder.tvCategoryTitle.setVisibility(View.GONE);
                }
            } else {//搜索得到的地区/国家
                holder.tvCategoryTitle.setVisibility(View.GONE);
                lp.rightMargin = 14;
                holder.tvNumber.setLayoutParams(lp);
            }
            return convertView;
        }

        private class ViewHolder {
            TextView tvCategoryTitle;
            TextView tvTitle;
            TextView tvNumber;
        }
    }

}
